package com.sto.stoapp.activity.scanner.upload;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.TabActivity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.ListView;
import android.widget.TabHost;
import android.widget.TabHost.OnTabChangeListener;
import android.widget.TabWidget;
import android.widget.TextView;
import android.widget.Toast;

import com.sto.stoapp.StoApplication;
import com.sto.stoapp.activity.R;
import com.sto.stoapp.activity.scanner.inquiry.InquiryFieldSql;
import com.sto.stoapp.activity.scanner.inquiry.InquiryQueryTable;
import com.sto.stoapp.adapter.InquirySelectAdapter;
import com.sto.stoapp.dataprocess.ProcessUploadData;
import com.sto.stoapp.db.StoTableName;
import com.sto.stoapp.listener.OnBackClickListener;
import com.sto.stoapp.listener.StoOnClickListener;
import com.sto.stoapp.manager.UnSentDataManager;
import com.sto.stoapp.status.EnumTableNames;
import com.sto.stoapp.thread.BaseThread;
import com.sto.stoapp.util.Helper;
import com.sto.stoapp.util.UnifiedStaticType;
import com.sto.stoapp.widget.BaseActivity;
import com.sto.stoapp.widget.BaseDialog;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;

import sto.android.app.StoPdaKeyEvent;

@SuppressLint("HandlerLeak")
@SuppressWarnings("deprecation")
public class UploadDataActivity extends TabActivity implements
		OnTabChangeListener {

	private ListView todayList;
	private ListView yesterdayList;
	private ListView beforeYesterdayList;
	private ListView everyoneDayList;
	private Button backToday, backYesterday, backBeforeYesterday, backEveryDay;
	private Button againUploadToday, againUploadYesterday,
			againUploadBeforeYesterday, againUploadEveryDay;
	private Button uploadToday, uploadYesterday, uploadBeforeYesterday,
			uploadEveryDay;

	private final int INT_TODAY = 0;// 今天
	private final int INT_YESTERDAY = 1;// 昨天
	private final int INT_BEFORE_YESTERDAY = 2;// 前天
	private final int INT_EVERYONE_DAY = 3;// 任意一天
	private final int RESULT = 0x11;
	private int dateItem = -1;
	private int tableItem = -2;

	// ISCLICK=false表示点击了事件，true没点击
	private Boolean ISCLICK = true;

	private final String TODAY = "today";
	private final String YESTERDAY = "yesterday";
	private final String BEFORE_YESTERDAY = "before_yesterday";
	private final String EVERYONE_DAY = "everyoneDay";

	private String listItemText;// 获取上级点击记录查询名称

	private InquirySelectAdapter courierAdapter;
	// private InquiryStatisticsAdapter statisticsAdapter;
	// private List<StatisticsEntity> statisticsList;
	private TabHost myTabhost;
	private InquiryFieldSql fieldSql;
	private StoTableName stoTableName;
	private List<HashMap<String, String>> courierDatas = new ArrayList<HashMap<String, String>>();

	private SendBroad sendBroad;
	private boolean hasUpData = true; // 是否有数据上传

	@SuppressLint({ "SimpleDateFormat", "ResourceAsColor" })
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);

		// requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);

		// 设置标题框
		// getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE,
		// R.layout.sto_title_layout);

		// listItemText = this.getIntent().getStringExtra("inquiryItemText");
		//
		// TextView title = (TextView) findViewById(R.id.title);
		// title.setText(listItemText);

		myTabhost = this.getTabHost();

		LayoutInflater.from(this).inflate(R.layout.sto_inquiry_layoutlist,
				myTabhost.getTabContentView(), true);

		tableItem = this.getIntent().getIntExtra("inquiryTableItem", -1);

		fieldSql = new InquiryFieldSql();
		stoTableName = new StoTableName();

		initWidget();
		// 设置tabweight背景色
		// myTabhost.setBackgroundColor(Color.parseColor("#000000"));
		myTabhost.setBackgroundColor(R.color.black);
		// myTabhost.setBackgroundResource(R.drawable.tabhost_bg);

		addTabHost();
		myTabhost.setOnTabChangedListener(this);
		setTabWeightFocus();
		// 监听任意一天的tab
		myTabhost.getTabWidget().getChildAt(INT_EVERYONE_DAY)
				.setOnClickListener(everyClickListener);
		onTabChanged(TODAY);
		myTabhost.setCurrentTab(0);// 设置默认选中项
	}

	/**
	 * 初始化控件ID
	 */
	private void initWidget() {
		backToday = (Button) findViewById(R.id.back_today);
		backYesterday = (Button) findViewById(R.id.back_yesterday);
		backBeforeYesterday = (Button) findViewById(R.id.back_before_yesterday);
		backEveryDay = (Button) findViewById(R.id.back_everyday);

		backToday.setOnClickListener(ClickListener);
		backYesterday.setOnClickListener(ClickListener);
		backBeforeYesterday.setOnClickListener(ClickListener);
		backEveryDay.setOnClickListener(ClickListener);

		againUploadToday = (Button) findViewById(R.id.text_today);
		againUploadYesterday = (Button) findViewById(R.id.text_yesterday);
		againUploadBeforeYesterday = (Button) findViewById(R.id.text_before_yesterday);
		againUploadEveryDay = (Button) findViewById(R.id.text_everyday);

		againUploadToday
				.setBackgroundResource(R.drawable.reupload_btn_selector);
		againUploadYesterday
				.setBackgroundResource(R.drawable.reupload_btn_selector);
		againUploadBeforeYesterday
				.setBackgroundResource(R.drawable.reupload_btn_selector);
		againUploadEveryDay
				.setBackgroundResource(R.drawable.reupload_btn_selector);

		againUploadToday.setOnClickListener(againUploadListener);
		againUploadYesterday.setOnClickListener(againUploadListener);
		againUploadBeforeYesterday.setOnClickListener(againUploadListener);
		againUploadEveryDay.setOnClickListener(againUploadListener);

		uploadToday = (Button) findViewById(R.id.left_today_button);
		uploadYesterday = (Button) findViewById(R.id.left_yesterday_button);
		uploadBeforeYesterday = (Button) findViewById(R.id.left_before_yesterday_button);
		uploadEveryDay = (Button) findViewById(R.id.left_everyday_button);

		uploadToday.setBackgroundResource(R.drawable.upload_btn_selector);
		uploadYesterday.setBackgroundResource(R.drawable.upload_btn_selector);
		uploadBeforeYesterday
				.setBackgroundResource(R.drawable.upload_btn_selector);
		uploadEveryDay.setBackgroundResource(R.drawable.upload_btn_selector);

		uploadToday.setOnClickListener(uploadListener);
		uploadYesterday.setOnClickListener(uploadListener);
		uploadBeforeYesterday.setOnClickListener(uploadListener);
		uploadEveryDay.setOnClickListener(uploadListener);

		todayList = (ListView) findViewById(R.id.inquiry_todayList);
		yesterdayList = (ListView) findViewById(R.id.inquiry_yesterdayList);
		beforeYesterdayList = (ListView) findViewById(R.id.inquiry_beforeYesterdayList);
		everyoneDayList = (ListView) findViewById(R.id.inquiry_everyoneDayList);

	}

	private void setTabWeightFocus() {
		myTabhost.getTabWidget().getChildAt(INT_TODAY).setFocusable(true);
		myTabhost.getTabWidget().getChildAt(INT_TODAY)
				.setFocusableInTouchMode(true);
		myTabhost.getTabWidget().getChildAt(INT_YESTERDAY)
				.setFocusableInTouchMode(true);
		myTabhost.getTabWidget().getChildAt(INT_BEFORE_YESTERDAY)
				.setFocusableInTouchMode(true);
		myTabhost.getTabWidget().getChildAt(INT_EVERYONE_DAY)
				.setFocusableInTouchMode(true);
		myTabhost.getTabWidget().getChildAt(INT_TODAY).requestFocus();
	}

	private void addTabHost() {

		myTabhost.addTab(myTabhost.newTabSpec(TODAY)
				.setIndicator(getString(R.string.today), null)
				.setContent(R.id.tabInquiry_today));

		myTabhost.addTab(myTabhost.newTabSpec(YESTERDAY)
				.setIndicator(getString(R.string.yesterday), null)
				.setContent(R.id.tabInquiry_yesterday));

		myTabhost.addTab(myTabhost.newTabSpec(BEFORE_YESTERDAY)
				.setIndicator(getString(R.string.before_yesterday), null)
				.setContent(R.id.tabInquiry_before_yesterday));

		myTabhost.addTab(myTabhost.newTabSpec(EVERYONE_DAY)
				.setIndicator(getString(R.string.everyoneday_month), null)
				.setContent(R.id.tabInquiry_everyoneDay));

		TabWidget tabWidget = this.getTabWidget();
		for (int i = 0; i < tabWidget.getChildCount(); i++) {
			TextView tv = (TextView) tabWidget.getChildAt(i).findViewById(
					android.R.id.title);
			tv.setTextColor(Color.WHITE);
		}
	}

	@SuppressLint("SimpleDateFormat")
	public boolean onCreateOptionsMenu(int myMenuSettingTag) {
		String tablename = EnumTableNames.values()[tableItem].getTableName();
		fieldSql.setInquirytablename(tablename);
		fieldSql.setIndex_id(tableItem);
		// fieldSql.setTitle_id(nameItem);

		switch (myMenuSettingTag) {
		case INT_TODAY:
			// againUploadToday.setText(getString(R.string.again_upload));
			// uploadToday.setText(getString(R.string.data_upload));
			SimpleDateFormat sDateFormat = new SimpleDateFormat(
					UnifiedStaticType.DATE_FORMAT);
			String date = sDateFormat.format(new java.util.Date());

			fieldSql.setInquiryField(new String[] { date });

			startInquiryActivity();
			break;
		case INT_YESTERDAY:
			// againUploadYesterday.setText(R.string.again_upload);
			// uploadYesterday.setText(getString(R.string.data_upload));
			Calendar cal = Calendar.getInstance();
			cal.add(Calendar.DATE, -1);
			String yesterdayDate = new SimpleDateFormat(
					UnifiedStaticType.DATE_FORMAT).format(cal.getTime());

			fieldSql.setInquiryField(new String[] { yesterdayDate });

			startInquiryActivity();
			break;
		case INT_BEFORE_YESTERDAY:

			// againUploadBeforeYesterday.setText(R.string.again_upload);
			// uploadBeforeYesterday.setText(getString(R.string.data_upload));
			Calendar cal1 = Calendar.getInstance();
			cal1.add(Calendar.DATE, -2);
			String beforeYesterdayDate = new SimpleDateFormat(
					UnifiedStaticType.DATE_FORMAT).format(cal1.getTime());

			fieldSql.setInquiryField(new String[] { beforeYesterdayDate });
			startInquiryActivity();
			break;
		case INT_EVERYONE_DAY:
			// againUploadEveryDay.setText(R.string.again_upload);
			// uploadEveryDay.setText(getString(R.string.data_upload));
			if (StoApplication.DeviceModel_420.equals(Helper.getPDAType()))
				show420Dialog();
			else
				showOtherDialog();
			/*
			 * final DatePicker datePicker = new DatePicker(this);
			 * AlertDialog.Builder builder = new AlertDialog.Builder(this);
			 * builder.setTitle("请选择日期")
			 * .setIcon(android.R.drawable.ic_dialog_info)
			 * .setView(datePicker).setNegativeButton("取消", null);
			 * 
			 * builder.setPositiveButton("查询月", new
			 * DialogInterface.OnClickListener() {
			 * 
			 * public void onClick(DialogInterface dialog, int which) {
			 * 
			 * int year = datePicker.getYear(); int month =
			 * datePicker.getMonth() + 1; String strMonth = null; if (0 < month
			 * && month < 10) { strMonth = "0" + month; } else { strMonth = "" +
			 * month; } String date = new StringBuilder().append("%")
			 * .append(strMonth).append("-").append("%")
			 * .append(year).toString(); fieldSql.setInquiryField(new String[] {
			 * date }); startInquiryActivity(); } }) .setNeutralButton("查询日",
			 * new DialogInterface.OnClickListener() {
			 * 
			 * @Override public void onClick(DialogInterface dialog, int which)
			 * {
			 * 
			 * int year = datePicker.getYear(); int month =
			 * datePicker.getMonth() + 1; int dayOfMonth =
			 * datePicker.getDayOfMonth(); String strMonth = null; String
			 * strDayOfMonth = null; if (0 < month && month < 10) { strMonth =
			 * "0" + month; } else { strMonth = "" + month; } if (0 < dayOfMonth
			 * && dayOfMonth < 10) { strDayOfMonth = "0" + dayOfMonth; } else {
			 * strDayOfMonth = "" + dayOfMonth; } String time = new
			 * StringBuilder() .append(strMonth).append("-")
			 * .append(strDayOfMonth).append("-") .append(year).toString();
			 * fieldSql.setInquiryField(new String[] { time });
			 * startInquiryActivity();
			 * 
			 * } }).create(); builder.show();
			 */

			break;
		default:
			break;
		}
		return false;
	}

	protected void show420Dialog() {

		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle("请选择日期");
		final DatePicker datePicker = new DatePicker(this);
		builder.setView(datePicker);
		final AlertDialog diag = builder.create();

		diag.setButton(DialogInterface.BUTTON1, "查询月",
				new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						int year = datePicker.getYear();
						int month = datePicker.getMonth() + 1;
						String strMonth = null;
						if (0 < month && month < 10) {
							strMonth = "0" + month;
						} else {
							strMonth = "" + month;
						}
						String date = new StringBuilder().append("%")
								.append(strMonth).append("-").append("%")
								.append(year).toString();
						fieldSql.setInquiryField(new String[] { date });
						diag.dismiss();
						startInquiryActivity();
					}
				});

		diag.setButton(DialogInterface.BUTTON3, "查询日",
				new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						int year = datePicker.getYear();
						int month = datePicker.getMonth() + 1;
						int dayOfMonth = datePicker.getDayOfMonth();
						String strMonth = null;
						String strDayOfMonth = null;
						if (0 < month && month < 10) {
							strMonth = "0" + month;
						} else {
							strMonth = "" + month;
						}
						if (0 < dayOfMonth && dayOfMonth < 10) {
							strDayOfMonth = "0" + dayOfMonth;
						} else {
							strDayOfMonth = "" + dayOfMonth;
						}
						String time = new StringBuilder().append(strMonth)
								.append("-").append(strDayOfMonth).append("-")
								.append(year).toString();
						fieldSql.setInquiryField(new String[] { time });
						diag.dismiss();
						startInquiryActivity();
					}
				});

		diag.setButton(DialogInterface.BUTTON2, "取消",
				new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						diag.dismiss();
					}
				});
		diag.show();

	}

	private static final int DATE_DIALOG_ID = 1;

	@TargetApi(Build.VERSION_CODES.HONEYCOMB)
	@SuppressLint("NewApi")

	private void showOtherDialog() {

		final DatePickerDialog diag;
		Calendar c = Calendar.getInstance();

			diag = new DatePickerDialog(this, null, c.get(Calendar.YEAR),
					c.get(Calendar.MONTH), c.get(Calendar.DAY_OF_MONTH));
			diag.setTitle("请选择日期");
			diag.setButton(DialogInterface.BUTTON1, "查询月",
					new DialogInterface.OnClickListener() {

						@SuppressLint("NewApi")
						@Override
						public void onClick(DialogInterface dialog, int which) {
							// TODO Auto-generated method stub
							int year = diag.getDatePicker().getYear();
							int month = diag.getDatePicker().getMonth() + 1;
							String strMonth = null;
							if (0 < month && month < 10) {
								strMonth = "0" + month;
							} else {
								strMonth = "" + month;
							}
							String date = new StringBuilder().append("%")
									.append(strMonth).append("-").append("%")
									.append(year).toString();
							fieldSql.setInquiryField(new String[] { date });
							diag.dismiss();
							startInquiryActivity();
						}
					});

			diag.setButton(DialogInterface.BUTTON3, "查询日",
					new DialogInterface.OnClickListener() {

						@SuppressLint("NewApi")
						@Override
						public void onClick(DialogInterface dialog, int which) {
							// TODO Auto-generated method stub
							int year = diag.getDatePicker().getYear();
							int month = diag.getDatePicker().getMonth() + 1;
							int dayOfMonth = diag.getDatePicker()
									.getDayOfMonth();
							String strMonth = null;
							String strDayOfMonth = null;
							if (0 < month && month < 10) {
								strMonth = "0" + month;
							} else {
								strMonth = "" + month;
							}
							if (0 < dayOfMonth && dayOfMonth < 10) {
								strDayOfMonth = "0" + dayOfMonth;
							} else {
								strDayOfMonth = "" + dayOfMonth;
							}
							String time = new StringBuilder().append(strMonth)
									.append("-").append(strDayOfMonth)
									.append("-").append(year).toString();
							fieldSql.setInquiryField(new String[] { time });
							diag.dismiss();
							startInquiryActivity();
						}
					});

			diag.setButton(DialogInterface.BUTTON2, "取消",
					new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {
							// TODO Auto-generated method stub
							diag.dismiss();
						}
					});
			diag.show();
		
	}

	@Override
	public void onTabChanged(String tabId) {

		if (!ISCLICK)
			return;
		dateItem = -1;
		if (tabId.equals(TODAY)) {
			dateItem = INT_TODAY;
		} else if (tabId.equals(YESTERDAY)) {
			dateItem = INT_YESTERDAY;
		} else if (tabId.equals(BEFORE_YESTERDAY)) {
			dateItem = INT_BEFORE_YESTERDAY;
		} else if (tabId.equals(EVERYONE_DAY)) {
			dateItem = INT_EVERYONE_DAY;
		}

		onCreateOptionsMenu(dateItem);
	}

	/**
	 * 监听点击记录信息
	 */
	StoOnClickListener ClickListener = new StoOnClickListener(this) {

		@Override
		public void mHonClick(View view) {
			finish();
		}
	};

	/**
	 * 监听重传
	 */
	StoOnClickListener againUploadListener = new StoOnClickListener(this) {

		@Override
		public void mHonClick(View view) {
			if (courierDatas.size() > 0) {
				final BaseDialog dialog = new BaseDialog(
						UploadDataActivity.this);
				dialog.setTitles(getString(R.string.determine_again_upload));
				dialog.show();
				dialog.setOnBackClickListener(new OnBackClickListener() {

					@Override
					public void onBackClickListener(boolean res) {
						if (res) {
							ArrayList<Integer> list = new ArrayList<Integer>();
							list.add(tableItem);
							Intent intent = new Intent(
									UnifiedStaticType.UP_ACTION);
							// 表
							// intent.putExtra(UnifiedStaticType.UPLOAD_TYPE,
							// list);
							intent.putIntegerArrayListExtra(
									UnifiedStaticType.UPLOAD_TYPE, list);
							// 日期
							intent.putExtra(
									UnifiedStaticType.AGAIN_UPLOAD_DATE,
									courierDatas.get(0).get(
											fieldSql.INQUIRYDATE));
							sendBroadcast(intent);
							Helper.showToast(UploadDataActivity.this,
									"正在上传中,请稍后查看...");

							dialog.dismiss();

							UploadDataActivity.this.finish();
						}
					}
				});

			} else {
				Helper.showToast(UploadDataActivity.this, "没有数据需要重传!");
			}
		}
	};

	/**
	 * 监听上传
	 */
	StoOnClickListener uploadListener = new StoOnClickListener(this) {

		@Override
		public void mHonClick(View view) {
			uploadData();
		}
	};

	/**
	 * 监听任意一天tabWeight
	 */
	StoOnClickListener everyClickListener = new StoOnClickListener(this) {

		@Override
		public void mHonClick(View view) {
			ISCLICK = false;
			myTabhost.setCurrentTab(INT_EVERYONE_DAY);// 设置选中项3
			dateItem = INT_EVERYONE_DAY;
			onCreateOptionsMenu(dateItem);
			ISCLICK = true;
		}
	};

	private void startInquiryActivity() {
		if (courierDatas.size() > 0) {
			courierDatas.clear();
			courierAdapter.notifyDataSetChanged();
		}
		if (bufferThread != null) {
			bufferThread.cancelDialog();
			bufferThread = null;
		}
		startBufferThread();
	}

	BufferThread bufferThread;

	private void startBufferThread() {
		bufferThread = new BufferThread(this);
		bufferThread.start();
	}

	Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			super.handleMessage(msg);

			if (msg.what == RESULT) {
				showToast(msg.obj.toString());
				// InquirySelectActivity.this.finish();
			}
		}
	};

	/**
	 * 查询数据缓冲线程
	 * 
	 * @author Administrator
	 * 
	 */
	class BufferThread extends BaseThread {
		private Context context;

		public BufferThread(Context context) {
			super(context);
			this.context = context;
			showDialog();
		}

		@Override
		public void run() {
			super.run();
			int count = 0;

			InquiryQueryTable querytable = new InquiryQueryTable(context);
			courierDatas = querytable.queryAll(fieldSql);
			count = courierDatas == null ? 0 : courierDatas.size();
			cancelDialog();
			if (count == 0) {
				Message msg = handler.obtainMessage();
				msg.what = RESULT;
				msg.obj = "无记录信息";
				handler.sendMessage(msg);
				hasUpData = false;
				return;
			}

			hasUpData = querytable.getHasUnsend();

			runOnUiThread(new Runnable() {
				@Override
				public void run() {
					courierAdapter = new InquirySelectAdapter(context,
							courierDatas, fieldSql);
					switch (dateItem) {
					case INT_TODAY:
						todayList.setAdapter(courierAdapter);
						break;
					case INT_YESTERDAY:
						yesterdayList.setAdapter(courierAdapter);
						break;
					case INT_BEFORE_YESTERDAY:
						beforeYesterdayList.setAdapter(courierAdapter);
						break;
					case INT_EVERYONE_DAY:
						everyoneDayList.setAdapter(courierAdapter);
						break;
					default:
						break;
					}
				}

			});
		}
	}

	private void showToast(String content) {
		Toast.makeText(this, content, Toast.LENGTH_LONG).show();
	}

	// 监听按键
	@Override
	public boolean onKeyUp(int keyCode, KeyEvent event) {
		keyCode=StoApplication.getStoJni().getEventFuction(keyCode);
		switch (keyCode) {
		case StoPdaKeyEvent.KEYCODE_1:
			Intent intentUpAll = new Intent(UnifiedStaticType.UP_ACTION);
			intentUpAll.putIntegerArrayListExtra(UnifiedStaticType.UPLOAD_TYPE,
					new ProcessUploadData().sendAllData());
			sendBroadcast(intentUpAll);
			break;
		case StoPdaKeyEvent.KEYCODE_SOFT_LEFT:
			uploadData();
			break;
		default:
			break;
		}
		return super.onKeyUp(keyCode, event);
	}

	/**
	 * 上传数据
	 */
	private void uploadData() {
		if (hasUpData) {
			ArrayList<Integer> list = new ArrayList<Integer>();
			list.add(tableItem);
			Intent intentUp = new Intent(UnifiedStaticType.UP_ACTION);
			intentUp.putIntegerArrayListExtra(UnifiedStaticType.UPLOAD_TYPE,
					list);
			sendBroadcast(intentUp);

			Helper.showToast(this, "正在上传中,请稍后查看...");
			this.finish();
		} else {
			Helper.showToast(this, "没有数据需要上传!");
		}
	}

	private Handler updateHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			if (msg.what == BaseActivity.UPDATE_SEND) {
				// int unSend = UnSentDataManager.getInstance().getUnSent() -
				// msg.arg1;
				// UnSentDataManager.getInstance().setUnSent(unSend);
				UnSentDataManager.getInstance().deleteCodeNumber(msg.arg1);
				System.out.println("updateSetUnSendCount msg.arg1:" + msg.arg1);
			}
		}
	};

	class SendBroad extends BroadcastReceiver {

		@Override
		public void onReceive(Context arg0, Intent arg1) {
			if (arg1.getAction().equals(BaseActivity.SEND_ACTION)) {
				int count = arg1.getIntExtra(BaseActivity.SEND_COUNT, 0);
				Message msg = updateHandler.obtainMessage();
				msg.what = BaseActivity.UPDATE_SEND;
				msg.arg1 = count;
				updateHandler.sendMessage(msg);
				System.out.println("onReceive SendBroad" + count);
			}
		}
	}

	@Override
	protected void onResume() {
		super.onResume();
		if (sendBroad == null) {
			sendBroad = new SendBroad();
			IntentFilter filter = new IntentFilter(BaseActivity.SEND_ACTION);
			registerReceiver(sendBroad, filter);
		}
	}

	@Override
	protected void onPause() {
		if (sendBroad != null) {
			unregisterReceiver(sendBroad);
			sendBroad = null;
		}
		super.onPause();
	}

	@Override
	protected void onDestroy() {
		if (sendBroad != null) {
			unregisterReceiver(sendBroad);
			sendBroad = null;
		}

		courierDatas.clear();
		if (myTabhost != null) {
			myTabhost.clearAllTabs();
			myTabhost = null;
		}
		if (bufferThread != null) {
			bufferThread.cancelDialog();
		}
		handler.removeMessages(RESULT);
		updateHandler.removeMessages(BaseActivity.UPDATE_SEND);
		super.onDestroy();
	}
}
